package com.xunce.xcworkservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xunce.xcworkservice.Enums.Enums;
import com.xunce.xcworkservice.dao.AccountDepartmentMapper;
import com.xunce.xcworkservice.dao.AccountMapper;
import com.xunce.xcworkservice.dao.AccountVerifyMapper;
import com.xunce.xcworkservice.entity.*;
import com.xunce.xcworkservice.exception.CustomException;
import com.xunce.xcworkservice.service.AccountService;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunce.xcworkservice.dao.DepartmentMapper;
import com.xunce.xcworkservice.service.DepartmentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService{


    private final AccountDepartmentMapper accountDepartmentMapper;

    private final AccountMapper accountMapper;

    private final AccountVerifyMapper accountVerifyMapper;

    @Override
    public Map<Integer, Department> getDepartmentMap(){

        List<Department> departments = list();

        List<Department> level1 = departments.stream().filter(department -> department.getDepartType().shortValue() == Enums.DepartmentType.LEVEL1.getValue()).toList();
        Map<Integer, Department> departmentDtoMap = new HashMap<>();
        for (Department department : level1){
            Department newD = new Department();
            BeanUtils.copyProperties(department, newD);
            newD.setNameAll(department.getName());
            departmentDtoMap.put(department.getDepartmentId(), newD);
        }

        List<Department> level2 = departments.stream().filter(department -> department.getDepartType().shortValue() == Enums.DepartmentType.LEVEL2.getValue()).toList();
        for (Department department : level2){
            Department newD = new Department();
            BeanUtils.copyProperties(department, newD);
            Department first = departmentDtoMap.get(department.getFirstId());
            newD.setNameAll(first.getName() + "-" + department.getName());
            departmentDtoMap.put(department.getDepartmentId(), newD);
        }

        List<Department> level3 = departments.stream().filter(department -> department.getDepartType().shortValue() == Enums.DepartmentType.LEVEL3.getValue()).toList();
        for (Department department : level3){
            Department newD = new Department();
            BeanUtils.copyProperties(department, newD);
            Department second = departmentDtoMap.get(department.getSecondId());
            newD.setNameAll(second.getNameAll() + "-" + department.getName());
            departmentDtoMap.put(department.getDepartmentId(), newD);
        }

        return departmentDtoMap;
    }

    // 更新用户部门信息
    @Override
    public Boolean updateAccountDepartment(Integer accountId, List<Integer> departmentIds) {
        QueryWrapper<AccountDepartment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AccountDepartment::getAccountId, accountId);
        List<AccountDepartment> accountDepartmentList = accountDepartmentMapper.selectList(wrapper);
        List<Integer> oldDepartmentIds = accountDepartmentList.stream().map(AccountDepartment::getDepartmentId).toList();
        if (departmentIds.equals(oldDepartmentIds)){
            return true;
        }
        //删除旧的
        if (oldDepartmentIds.size() > 0){
            LambdaQueryWrapper<AccountDepartment> delWrapper = new LambdaQueryWrapper<>();
            delWrapper.eq(AccountDepartment::getAccountId, accountId);
            accountDepartmentMapper.delete(delWrapper);
        }
        //添加新的
        for (Integer departmentId : departmentIds){
            AccountDepartment accountDepartment = new AccountDepartment();
            accountDepartment.setAccountId(accountId);
            accountDepartment.setDepartmentId(departmentId);
            accountDepartmentMapper.insert(accountDepartment);
        }
        return true;
    }

    @Override
    public List<Department> getTreeList() {
        List<Department> allDepartments = list();

        List<Account> accounts = accountMapper.selectList(null);
        Map<Integer, String> accountMap = accounts.stream().collect(Collectors.toMap(Account::getAccountId, obj ->
            StringUtils.isBlank(obj.getAccountName()) ? obj.getEnName() : obj.getAccountName()));

        Map<Integer, Department> departmentMap = new HashMap<>();
        // 将所有部门按照ID放入Map中，方便后续查找
        for (Department department : allDepartments) {
            if (department.getReviewUid() != null){
                department.setReviewAccountName(accountMap.getOrDefault(department.getReviewUid(), ""));
            }
            if (department.getOwnerUid() != null){
                department.setOwnerName(accountMap.getOrDefault(department.getOwnerUid(), ""));
            }
            departmentMap.put(department.getDepartmentId(), department);
        }

        List<Department> tree = new ArrayList<>();

        // 遍历所有部门，构建树形结构
        for (Department department : allDepartments) {
            if (department.getDepartType() == 1) {
                // 一级部门直接添加到树中
                tree.add(department);
            } else {
                // 二级及以下部门添加到父部门的childrenList中
                int parentId = (department.getDepartType() == 2) ? department.getFirstId() : department.getSecondId();
                Department parentDepartment = departmentMap.get(parentId);

                if (parentDepartment != null) {
                    parentDepartment.getChildrenList().add(department);
                }
            }
        }
        return tree;

    }

    @Transactional
    @Override
    public boolean edit(Department department) {
        return saveOrUpdate(department);
    }

    @Override
    public List<AccountVerify> getVerifyList(){
        List<AccountVerify> accountVerifies = accountVerifyMapper.selectList(null);
        List<Account> accountList = accountMapper.selectList(null);
        Map<Integer, String> accountMap = accountList.stream().collect(Collectors.toMap(Account::getAccountId, obj -> obj.getAccountName() + " " + obj.getEnName()));
        List<Department> departments = list();
        Map<Integer, String> departmentMap = departments.stream().collect(Collectors.toMap(Department::getDepartmentId, Department::getName));
        for (AccountVerify accountVerify : accountVerifies){
            List<Integer> departmentList = Arrays.stream(accountVerify.getDepartments().split(","))
                    .map(Integer::parseInt)
                    .toList();
            List<String> nameArr = new ArrayList<>();
            for (Integer departmentId : departmentList){
                nameArr.add(departmentMap.getOrDefault(departmentId, "空部门"));
            }

            accountVerify.setAccountName(accountMap.getOrDefault(accountVerify.getAccountId(), ""));
            accountVerify.setDepartmentNames(String.join(",", nameArr));
        }
        return accountVerifies;
    }

    @Override
    public boolean verifyDelete(Integer id) {
        return accountVerifyMapper.deleteById(id) > 0;
    }

    @Override
    public boolean verifyEdit(AccountVerify accountVerify){

        if (accountVerify.getId() == null){
            QueryWrapper<AccountVerify> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(AccountVerify::getAccountId, accountVerify.getAccountId());
            long count = accountVerifyMapper.selectCount(queryWrapper);
            if (count > 0){
                throw new RuntimeException("当前员工已经设置 不可重复");
            }
           return accountVerifyMapper.insert(accountVerify) > 0;
        }
        UpdateWrapper<AccountVerify> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(AccountVerify::getId, accountVerify.getId())
                .set(AccountVerify::getDepartments, accountVerify.getDepartments());
        return accountVerifyMapper.update(wrapper) > 0;

    }

    @Override
    public boolean checkDelete(Integer id) throws CustomException {
        QueryWrapper<AccountDepartment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AccountDepartment::getDepartmentId, id);
        List<AccountDepartment> accountDepartmentList = accountDepartmentMapper.selectList(wrapper);
        if (accountDepartmentList != null && accountDepartmentList.size() > 0){
            throw new CustomException("当前部门使用中无法删除", 50001);
        }
        return removeById(id);
    }
}
